﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Runtime.InteropServices;

namespace SELF.Controls
{
    public partial class frm_player : DevExpress.XtraEditors.XtraForm
    {
        public frm_player()
        {
            InitializeComponent();
            this.FormClosing += new FormClosingEventHandler(frm_player_FormClosing);
        }

        void frm_player_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.Dispose();
            
            //throw new NotImplementedException();
        }

        SELF.Controls.PlayerControl ctrl = new PlayerControl();
        lcmpt.Connection conn = new lcmpt.Connection();

        private string courseID = "";
        private int EndOfReserv = 0;
        private int serverTime = 0;
        private string logOnTicket;

        public string LogOnTicket
        {
            get { return logOnTicket; }
            set { logOnTicket = value; }
        }

        System.Windows.Forms.Timer tmCheckEndReserv = new Timer();

        System.Windows.Forms.Timer tmTime = new Timer();

        System.Windows.Forms.Timer tmSeek = new Timer();

        private void Init()
        {
            WMplayer.uiMode = "none";

            this.WindowState = FormWindowState.Maximized;

            Application.AddMessageFilter(new IgnoreMouseClickMessageFilter(this,WMplayer));
            tmTime.Interval = 1000;
            tmTime.Tick += new EventHandler(tmTime_Tick);

            tmSeek.Interval = 800;
            tmSeek.Tick += new EventHandler(tmSeek_Tick);
            
            //courseID = 
            SELF.Model.Leaning.SetMechineState(SELF.Model.Leaning.StateMechine.Play);
            EndOfReserv = EndTime();
        }

        void tmSeek_Tick(object sender, EventArgs e)
        {
            if ((SELF.VDOStatus.seekBuffer==1) && SELF.VDOStatus.unSeeking)
            {
                WMplayer.Ctlcontrols.currentPosition = SELF.VDOStatus.seekLen;
                SELF.VDOStatus.seekBuffer = 0;
            }

            #region button click
            if (SELF.VDOStatus.playerStatus == VDOStatus.PlayerStatus.Pause)
            {
                WMplayer.Ctlcontrols.pause();
            }
            if (SELF.VDOStatus.playerStatus == VDOStatus.PlayerStatus.Play)
            {
                WMplayer.Ctlcontrols.play();
            }
            if (SELF.VDOStatus.playerStatus == VDOStatus.PlayerStatus.Stop)
            {
                tmSeek.Stop();
                WMplayer.Ctlcontrols.pause();
                SELF.Dialog_Close clsDiag = new Dialog_Close();
                clsDiag.ShowDialog();
                if (clsDiag.DialogResult == DialogResult.Yes)
                {
                    WMplayer.Ctlcontrols.stop();
                    string sqlStopVDO = @"UPDATE [dbo].[Dim_TicketHistory]
                      SET EndTime = GETDATE()
                      WHERE ID = (SELECT MAX(ID) 
                      FROM [dbo].[Dim_TicketHistory] 
                      WHERE TicketID = '@TicketID')";
                    sqlStopVDO = sqlStopVDO.Replace("@TicketID", LogOnTicket);
                    clsDiag.Close();
                    ctrl.Close();
                    tmTime.Stop();
                    tmSeek.Stop();
                    SELF.VDOStatus.playerStatus = VDOStatus.PlayerStatus.Play;
                    //WMplayer.close();
                    this.Close();
                }
                else
                {
                    SELF.VDOStatus.playerStatus = VDOStatus.PlayerStatus.Play;
                    WMplayer.Ctlcontrols.play();
                    tmSeek.Start();
                }
            }
            #endregion

            //throw new NotImplementedException();
        }

        void tmTime_Tick(object sender, EventArgs e)
        {
            try
            {
                WMplayer.settings.volume = SELF.VDOStatus.volumn;
                WMplayer.settings.rate = SELF.VDOStatus._WMPRate;                
                SELF.VDOStatus.totalLen = WMplayer.currentMedia.duration;
                SELF.VDOStatus.currentLen = WMplayer.Ctlcontrols.currentPosition;

                SELF.VDOStatus.txtCurrentLen = WMplayer.Ctlcontrols.currentPositionString;
                SELF.VDOStatus.txtTotalLen = WMplayer.currentMedia.durationString;

                if (WMplayer.playState == WMPLib.WMPPlayState.wmppsStopped)
                {
                    ctrl.Close();
                    tmTime.Stop();
                    this.Close();
                }

                #region waiting time

                SELF.VDOStatus.idleTime += 1;

                if (SELF.VDOStatus.idleTime == 20)
                {
                    ctrl.Opacity = 0;
                }
                #endregion

                if ((SELF.VDOStatus.currentLen > SELF.VDOStatus.totalLen-2) && SELF.VDOStatus.currentLen > 1)
                {
                    WMplayer.Ctlcontrols.stop();
                    ctrl.Close();
                    tmTime.Stop();
                    tmSeek.Stop();
                    //WMplayer.close();
                    this.Close();
                }

                if (VDOStatus._CountDownInSec < 2)
                {
                    WMplayer.Ctlcontrols.stop();
                    thStopAtEnd.Abort();
                    cGobal.EndOfReserv = true;
                    
                    //WMplayer.close();
                    ctrl.Close();
                    tmTime.Stop();
                    tmSeek.Stop();
                    this.Close();
                }
                
                //Add check reservation end here
            }
            catch (Exception ex)
            {
                tmTime.Stop();
                tmSeek.Stop();
                this.Close();
                this.Dispose();
                //code here.
            }
        }


        public void StopAtEnd()
        {
            bool FA = true;
            while (FA)
            {
                if (VDOStatus._CountDownInSec == 900)
                {
                    MessageBoxCustom message = new MessageBoxCustom("เหลือเวลาจอง 15 นาที\nหากต้องการจองเวลาเพิ่ม ให้เลือกเมนู \"จองคอร์สเรียน\" ในหน้าหลัก", 0);
                }
                if (VDOStatus._CountDownInSec < 11)
                {
                    this.Invoke((MethodInvoker)delegate
                    {
                        MessageBoxCustom message = new MessageBoxCustom("เวลาการจองหมด และโปรแกรมจะปิดอัตโนมัติใน 10 วินาที", 10);
                        message.Show();
                        FA = false;
                    });
                    thStopAtEnd.Abort();
                }
                //System.Threading.Thread.Sleep(1000);
            }
           // int serverTime
        }

        private int EndTime()
        {
            try
            {
                int endTime = 0;
                string sqlMinEnd = @"SELECT MinEnd
                              FROM [dbo].Detail_Time
                              WHERE TimeId = (SELECT MAX(TimeId) 
                              FROM [dbo].[Booking]
                              WHERE [ROUND] = @dRound)";
                sqlMinEnd = sqlMinEnd.Replace("@dRound", SELF.VDOStatus.RoundLogin);
                using (DataSet ds = conn.Retreive(sqlMinEnd))
                {
                    if (ds != null && (ds.Tables[0].Rows.Count != 0))
                    {
                        endTime = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                    }
                }
                return endTime;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        #region fields
        private string fileName;
        private string fileType;
        #endregion

        #region property
        public string FileType
        {
            get { return fileType; }
            set { fileType = value; }
        }

        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }
        #endregion

        System.Threading.Thread thStopAtEnd;

        private void frm_player_Load(object sender, EventArgs e)
        {
            serverTime = SELF.Model.Leaning.TimeToValue(SELF.Model.Leaning.GetServerTime());

            thStopAtEnd = new System.Threading.Thread(new System.Threading.ThreadStart(StopAtEnd));
            thStopAtEnd.Start();

            Init();
            tmTime.Start();
            tmSeek.Start();
            
            ctrl.ScreenHeight = Screen.PrimaryScreen.Bounds.Height;
            ctrl.ScreenWidth = Screen.PrimaryScreen.Bounds.Width;
            ctrl.TopMost = true;
            ctrl.Show();

            System.Threading.AutoResetEvent waitEvent = new System.Threading.AutoResetEvent(false);


            //WMPLib player = new WMPLib.WindowsMediaPlayer();

            //WMplayer.PlayStateChange += new AxWMPLib._WMPOCXEvents_PlayStateChangeEventHandler(WMplayer_PlayStateChange);
            WMplayer.URL = Config.Configurations._ServerStorage +"\\"+ cGobal.GetCourseID(FileName)+ "\\" + FileName + FileType;
            //MessageBox.Show(WMplayer.URL);

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void WMplayer_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            //throw new NotImplementedException();
        }

        private void WMplayer_MouseDownEvent(object sender, AxWMPLib._WMPOCXEvents_MouseDownEvent e)
        {
            SELF.VDOStatus.idleTime = 0;
            for (int i = 0; i < 100; i++)
            {
                ctrl.Opacity = i;
            }
        }


    }
} 